package main

import (
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/rds"
	"github.com/jinzhu/configor"
)

func main() {
	dir := getCurrentPath()

	ipcache := filepath.Join(dir, "ipcache.txt")
	println(ipcache)
	ip := getIpBy3322()
	if len(ip) == 0 {
		println("get ip error.")
		return
	}
	println(ip)
	if checkFileExistence(ipcache) {
		temp, err := os.ReadFile(ipcache)
		if err != nil {
			println(err.Error())
			return
		}
		if string(temp) == ip {
			println("ip not update")
			return
		}
	}
	conf := new(Config)
	configPath := filepath.Join(dir, "config.yml")
	err := configor.Load(conf, configPath)
	if err != nil {
		println(err.Error())
		return
	}
	client, err := rds.NewClientWithAccessKey(conf.RegionID, conf.AccessKeyID, conf.AccessKeySecret)
	if err != nil {
		println(err.Error())
		return
	}
	req := rds.CreateModifySecurityIpsRequest()
	req.DBInstanceId = conf.InstanceId
	req.SecurityIps = ip
	req.DBInstanceIPArrayName = conf.IpGroupName
	resp, err := client.ModifySecurityIps(req)
	if err != nil {
		println(err.Error())
		return
	}

	println(resp.IsSuccess())
	err = os.WriteFile(ipcache, []byte(ip), 0777)
	if err != nil {
		println(err.Error())
	}
}

func getIpBy3322() string {
	client := &http.Client{Timeout: 10 * time.Second}
	req, err := http.NewRequest("GET", "http://members.3322.org/dyndns/getip", nil)
	if err != nil {
		println(err.Error())
		return ""
	}
	resp, err := client.Do(req)
	if err != nil {
		println(err.Error())
		return ""
	}
	if resp.StatusCode != http.StatusOK {
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			println(err.Error())
			return ""
		}
		println(string(body))
		return ""
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		println(err.Error())
		return ""
	}
	ip := string(body)
	ip = strings.Replace(ip, "\n", "", -1)
	ip = strings.Replace(ip, "\r", "", -1)
	ip = strings.Replace(ip, " ", "", -1)
	return ip
}

func checkFileExistence(filePath string) bool {
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return false
	} else if err == nil {
		return true
	}
	return false
}

func getCurrentPath() string {
	executablePath, _ := os.Executable()
	path, _ := filepath.Abs(filepath.Dir(executablePath))
	return path
}
